<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="6" :xs="6">
        <!--仓库-->
        <div class="head-container">
          <el-input v-model="storeName" placeholder="请输入仓库名称" clearable size="small" prefix-icon="el-icon-search"
            style="margin-bottom: 20px" />
        </div>
        <div class="head-container">
          <el-tree :data="storeOptions" :props="defaultProps" :expand-on-click-node="false"
            :filter-node-method="filterNode" ref="tree" default-expand-all @node-click="handleNodeClick" />
        </div>
      </el-col>
      <el-col :span="18" :xs="18">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="80px">
          <el-form-item label="部门" prop="deptId">
            <treeselect v-model="queryParams.deptId" :options="deptOptions" :show-count="true" placeholder="部门"
              style="width: 160px" size="small" />
          </el-form-item>
          <el-form-item label="类型" prop="type">
            <el-select v-model="queryParams.type" placeholder="请选择类型" clearable size="small">
              <el-option v-for="dict in dict.type.oms_task_type" :key="dict.value" :label="dict.label"
                :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="订单编号" prop="taskNo">
            <el-input v-model="queryParams.taskNo" placeholder="请输入订单编号" clearable size="small"
              @keyup.enter.native="handleQuery" />
          </el-form-item>
          <!-- <el-form-item label="仓库" prop="storeId">
        <el-input
          v-model="queryParams.storeId"
          placeholder="请输入仓库"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
          <el-form-item label="状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
              <el-option v-for="dict in dict.type.sys_common_status" :key="dict.value" :label="dict.label"
                :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="下单时间" prop="updateTime">
            <el-date-picker clearable size="small" v-model="queryParams.updateTime" type="date"
              value-format="yyyy-MM-dd" placeholder="请选择下单时间">
            </el-date-picker>
          </el-form-item>
          <!-- <el-form-item label="联系方式" prop="tel">
        <el-input
          v-model="queryParams.tel"
          placeholder="请输入联系方式"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
          <!-- <el-form-item label="姓名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入姓名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
          <!-- <el-form-item label="删除标识" prop="delFlag">
        <el-select v-model="queryParams.delFlag" placeholder="请选择删除标识" clearable size="small">
          <el-option
            v-for="dict in dict.type.sys_del_flag"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item> -->
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
              v-hasPermi="['oms:task:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
              v-hasPermi="['oms:task:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
              v-hasPermi="['oms:task:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
              v-hasPermi="['oms:task:export']">导出</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="el-icon-s-unfold" size="mini" :disabled="multiple" @click="handleSend"
              v-hasPermi="['oms:task:add']">下发</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="taskList" @selection-change="handleSelectionChange" border stripe>
          <el-table-column type="selection" width="55" align="center" />
          <!-- <el-table-column label="订单id" align="center" prop="id" v-if="true"/> -->
          <el-table-column label="类型" align="center" prop="type">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.oms_task_type" :value="scope.row.type" />
            </template>
          </el-table-column>
          <el-table-column label="订单编号" align="left" prop="taskNo" fixed="left" width="120" />
          <el-table-column label="部门" align="left" prop="deptName" fixed="left" width="160" />
          <el-table-column label="姓名" align="left" prop="name" fixed="left" width="100" />
          <el-table-column label="联系方式" align="left" prop="tel" fixed="left" width="120" />
          <el-table-column label="地址" align="left" prop="address" width="380" />
          <el-table-column label="仓库" align="left" prop="storeName" width="120" />
          <el-table-column label="物品数量" align="center" prop="nums" width="100" />
          <el-table-column label="审批人" align="left" prop="checkerName" width="100" />
          <el-table-column label="审批时间" align="left" prop="checkTime" width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.checkTime, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <!-- <el-table-column label="审批状态" align="center" prop="checkStatus" width="100" /> -->
          <el-table-column label="备注" align="left" prop="remark" width="280" />
          <el-table-column label="物流配送" align="center" prop="delivery" width="100">
            <template slot-scope="scope">
                <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.delivery" />
              </template>
            </el-table-column>
          <el-table-column label="状态" align="center" prop="status" width="80">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.sys_common_status" :value="scope.row.status" />
            </template>
          </el-table-column>
          <!-- <el-table-column label="经度" align="center" prop="lng" />
      <el-table-column label="纬度" align="center" prop="lat" /> -->

          <el-table-column label="操作" align="left" class-name="small-padding fixed-width" fixed="right" width="160">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['oms:task:edit']">修改</el-button>
              <el-button size="mini" type="text" icon="el-icon-s-unfold" @click="handleSend(scope.row)"
                  v-hasPermi="['oms:task:add']">下发</el-button>
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                v-hasPermi="['oms:task:remove']">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
          @pagination="getList" />
      </el-col>
    </el-row>
    <!-- 添加或修改出入库订单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1080px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-row :gutter="15">
          <el-col :span="8" v-if="form.taskNo">
            <el-form-item label="订单编号" prop="taskNo">
              <el-input v-model="form.taskNo" placeholder="请输入订单编号" />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择类型">
                <el-option v-for="dict in dict.type.oms_task_type" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
<el-col :span="8">
            <el-form-item label="仓库" prop="storeId">
              <treeselect v-model="form.storeId" :options="storeOptions" :show-count="true" placeholder="请选择仓库" />
            </el-form-item>
          </el-col>

        </el-row>

        <el-row :gutter="15">
          <el-col :span="8">
            <el-form-item label="部门" prop="deptId">
              <treeselect v-model="form.deptId" :options="deptOptions" :show-count="true" placeholder="部门"
                style="width: 160px" size="small" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系人" prop="name">
              <el-select v-model="form.name" placeholder="请选择联系人" @change="getUserMobile">
                <el-option v-for="item in contactsOptions" :key="item.id" :label="item.name"
                  :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系方式" prop="tel">
              <el-input v-model="form.tel" placeholder="请输入联系方式" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="15">
          <el-col :span="24">
            <el-form-item label="地址" prop="address">
              <el-input v-model="form.address" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :offset="2" :span="22">
            <el-card shadow="hover">
              <div slot="header" class="clearfix">
                <span>财物清单</span>
                <el-button type="text" style="float:right;padding: 3px 0" @click="addDtl">新增</el-button>
              </div>
              <el-table :data="form.items" border stripe>
                <el-table-column label="物品编号" align="center" prop="pno">
                  <template slot-scope="scope">
                   <el-input placeholder="请输入物品编号" v-model="scope.row.pno" />
                  </template>
                </el-table-column>
                <el-table-column label="物品名称" align="center" prop="name">
                  <template slot-scope="scope">
                    <el-input placeholder="请输入物品名称" v-model="scope.row.name" />
                  </template>
                </el-table-column>
                <el-table-column label="所在单位" align="center" prop="deptId">
                  <template slot-scope="scope">
                    <treeselect v-model="scope.row.deptId" :options="deptOptions" :show-count="true" append-to-body placeholder="所在单位"
                     size="small" z-index="9999" />
                  </template>
                </el-table-column>
                <el-table-column label="所在机构" align="center" prop="localId">
                  <template slot-scope="scope">
                    <treeselect v-model="scope.row.localId" :options="deptOptions" :show-count="true" append-to-body placeholder="所在机构"
                      size="small" z-index="9999" />
                  </template>
                </el-table-column>
                <el-table-column label="数量" align="center" prop="nums">
                  <template slot-scope="scope">
                    <el-input placeholder="请输入数量" v-model="scope.row.nums" />
                  </template>
                </el-table-column>
                <el-table-column label="操作" align="left">
                  <template slot-scope="scope">
                    <el-row>
                      <el-col>
                        <el-button type="danger" size="mini" @click="dtlDel(scope)" v-if="scope.row.delFlag == '0'">删除</el-button>
                        <el-tag type="info" v-if="scope.row.delFlag == '2'">已删除</el-tag>
                      </el-col>
                    </el-row>
                  </template>
                </el-table-column>
              </el-table>
            </el-card>
          </el-col>
        </el-row>
        <el-row :gutter="15" style="margin-top: 15px;">
          <!-- <el-col :span="8">
            <el-form-item label="物品数量" prop="nums">
              <el-input v-model="form.nums" placeholder="请输入物品数量" />
            </el-form-item>
          </el-col> -->
          <el-col :span="8">
            <el-form-item label="物流配送" prop="delivery">
              <el-radio-group v-model="form.delivery">
                <el-radio v-for="dict in dict.type.sys_yes_no" :key="dict.value" :label="dict.value">
                  {{dict.label}}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio v-for="dict in dict.type.sys_common_status" :key="dict.value" :label="dict.value">
                  {{dict.label}}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="15">
          <el-col :span="8">
            <el-form-item label="审批人" prop="checker">
              <el-select v-model="form.checker" placeholder="请选择审批人">
                <el-option v-for="item in userOptions" :key="item.userId" :label="item.nickName"
                  :value="item.userName" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="审批时间" prop="checkTime">
              <el-date-picker clearable size="small" v-model="form.checkTime" type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss" placeholder="请选择审批时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="15">
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <selectProperty  ref="elDrawer" @handleSelected="handleSelected"></selectProperty>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listTask,
    getTask,
    delTask,
    addTask,
    updateTask
  } from "@/api/oms/task";
  import {
    listStore,
    storeTreeselect
  } from "@/api/wms/store";
  import {
    contacts
  } from "@/api/oms/contacts";
  import {
    treeselect
  } from "@/api/system/dept";
  import {
    listUser
  } from "@/api/system/user";
  import {
    sendsTask
  } from "@/api/center/index";

  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  import selectProperty from "@/components/SelectProperty/index.vue";
  export default {
    name: "Task",
    dicts: ['sys_common_status', 'sys_del_flag', 'oms_task_type', 'sys_yes_no'],
    components: {
      Treeselect,
      selectProperty
    },
    data() {
      return {
        // 按钮loading
        buttonLoading: false,
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 出入库订单表格数据
        taskList: [],
        storeOptions: [],
        storeTree: [],
        storeName: undefined,
        deptOptions: [],
        userOptions: [],
        contactsOptions:[],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        defaultProps: {
          children: "children",
          label: "label"
        },
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          taskNo: undefined,
          type: undefined,
          storeId: undefined,
          checkStatus: undefined,
          deptId: undefined,
          status: undefined,
          updateTime: undefined,
          tel: undefined,
          name: undefined,
          delFlag: undefined
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          taskNo: [{
            required: true,
            message: "订单编号不能为空",
            trigger: "blur"
          }],
          type: [{
            required: true,
            message: "类型不能为空",
            trigger: "change"
          }],
          nums: [{
            required: true,
            message: "物品数量不能为空",
            trigger: "blur"
          }],
        }
      };
    },
    watch: {
      storeName(val) {
        this.$refs.tree.filter(val);
      },
      'queryParams.deptId': {
        handler(newVal, oldVal) {
          this.deptChange();
        },
        deep: true,
        immediate: true
      },
      'form.deptId': {
        handler(newVal, oldVal) {
          this.selectDeptId()
        }
      }
    },
    created() {
      this.getList();
      this.getStoreTreeselect();
      this.getTreeselect();
    },
    methods: {
      /** 查询出入库订单列表 */
      getList() {
        this.loading = true;
        listTask(this.queryParams).then(response => {
          this.taskList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      /** 查询分类下拉树结构 */
      getStoreTreeselect() {
        storeTreeselect().then(response => {
          this.storeOptions = response.data;
        });
      },
      /** 查询部门下拉树结构 */
      getTreeselect() {
        treeselect().then(response => {
          this.deptOptions = response.data;
        });
      },
      getUsers() {
        listUser({'deptId':this.form.deptId}).then(response => {
          this.userOptions = response.rows
        })
      },
      getUserMobile(e) {
        
        let _this = this;
        this.contactsOptions.forEach(item => {
          if (item.id == e) {
            
            _this.form.name = item.name;
            _this.form.tel = item.tel;
            _this.form.address = item.address;
            _this.form.lng = item.lng;
            _this.form.lat = item.lat;
          }
        });
      },
      getContacts(){
        contacts({'deptId':this.form.deptId}).then(response => {
          this.contactsOptions = response.data
        })
      },
      deptChange() {
        this.getList();
      },
      selectDeptId(){
        this.getUsers();
        this.getContacts();
      },
      // 筛选节点
      filterNode(value, data) {
        if (!value) return true;
        return data.label.indexOf(value) !== -1;
      },
      // 节点单击事件
      handleNodeClick(data) {
        this.queryParams.storeId = data.id;
        this.handleQuery();
      },
      normalizer(node) {
        if (node.children && !node.children.length) {
          delete node.children;
        }
        return {
          id: node.id,
          label: node.name,
          children: node.children
        };
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: undefined,
          taskNo: undefined,
          type: undefined,
          storeId: undefined,
          nums: undefined,
          checker: undefined,
          checkTime: undefined,
          checkStatus: "0",
          remark: undefined,
          delivery: 'Y',
          deptId: undefined,
          status: '0',
          createTime: undefined,
          createBy: undefined,
          updateTime: undefined,
          updateBy: undefined,
          lng: undefined,
          lat: undefined,
          address: undefined,
          tel: undefined,
          name: undefined,
          delFlag: '0',
          items: []
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加出入库订单";
        this.form.storeId = this.queryParams.storeId
        this.getContacts()
        this.$refs.elDrawer.getList()
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.loading = true;
        this.reset();
        const id = row.id || this.ids
        getTask(id).then(response => {
          this.loading = false;
          this.form = response.data;
          this.open = true;
          this.title = "修改出入库订单";
        });
        this.getContacts();
        this.$refs.elDrawer.getList()
      },
      addDtl(){
        // let data = {
        //   id: undefined,
        //   taskId: undefined,
        //   pno: undefined,
        //   name: undefined,
        //   deptId: undefined,
        //   localId: undefined,
        //   nums: undefined,
        //   delFlag: '0'
        // }
        // this.form.items.push(data)
        this.$refs.elDrawer.open()
      },
      dtlDel(scope){
        let index = scope.$index;
        if(this.form.items[index].id && this.form.items[index].id != ''){
          this.form.items[index].delFlag='2';
        }else{
          this.form.items.splice(index,1)
        }
      },
		//获取选择后的财务数据
      handleSelected(array){
        
        array.forEach(item=>{
          item.delFlag = '0'
          item.id=undefined
          this.form.items.push(item)
        })
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            this.buttonLoading = true;
            if (this.form.id != null) {
              updateTask(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }).finally(() => {
                this.buttonLoading = false;
              });
            } else {
              addTask(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }).finally(() => {
                this.buttonLoading = false;
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除出入库订单编号为"' + ids + '"的数据项？').then(() => {
          this.loading = true;
          return delTask(ids);
        }).then(() => {
          this.loading = false;
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).finally(() => {
          this.loading = false;
        });
      },
      handleSend(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认下发所选数据项？').then(() => {
          this.loading = true;
          return sendsTask(ids);
        }).then(() => {
          this.loading = false;
          this.getList();
          this.$modal.msgSuccess("下发成功");
        }).finally(() => {
          this.loading = false;
        });
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('oms/task/export', {
          ...this.queryParams
        }, `task_${new Date().getTime()}.xlsx`)
      }
    }
  };
</script>
